import socket
import threading

# 定义服务器的IP和端口
SERVER_HOST = '192.168.75.128'  # 替换为实际的服务器IP地址
SERVER_PORT = 12345

# 接收来自服务器的消息并打印
def receive_messages(client_socket):
    while True:
        try:
            message = client_socket.recv(1024).decode('utf-8')
            print(message)
        except:
            print("连接到服务器失败。")
            client_socket.close()
            break

def connect_to_server():
    """连接到服务器并返回套接字"""
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    try:
        client_socket.connect((SERVER_HOST, SERVER_PORT))
        print("已连接到服务器。")
        return client_socket
    except:
        print("无法连接到服务器。")
        return None

def main():
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    client_socket.connect((SERVER_HOST, SERVER_PORT))
    print("已连接到服务器。")

    # 启动线程来接收消息
    thread = threading.Thread(target=receive_messages, args=(client_socket,))
    thread.start()

    while True:
        # 从用户输入中获取消息并发送到服务器
        message = input("你：")
        if message.lower() == 'exit':
            client_socket.close()
            break
        client_socket.send(message.encode('utf-8'))

if __name__ == "__main__":
    main()
